package com.xg.frame.shiro;


import com.xg.frame.constant.Constant;
import com.xg.frame.utils.HttpContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author dehuisun
 * @create 2018-07-12 15:56
 * @desc
 **/
@Slf4j
public class JwtFilter extends AuthenticatingFilter {

    /**
     * 执行登录认证
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
    	 if(((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())){
             return true;
         }
         return super.isAccessAllowed(request, response, mappedValue);
    }

    /**
     *捕获token验证失败
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
        try {
            //处理登录失败的异常
            /*Throwable throwable = e.getCause() == null ? e : e.getCause();
            String json = JSONObject.fromObject(R.noAccess().info(throwable.getMessage())).toString();
            httpResponse.getWriter().print(json);*/
            String path = ((HttpServletRequest) request).getContextPath();
            httpResponse.sendRedirect(path);
        } catch (Exception exp) {
            log.error("token异常",exp);
        }

        return false;
    }

	@Override
	protected AuthenticationToken createToken(ServletRequest request,
			ServletResponse response) throws Exception {
		  //获取请求token
        String token = getRequestToken((HttpServletRequest) request);
        if(StringUtils.isBlank(token)){
            return null;
        }
        return new JwtToken(token);
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		 //获取请求token，如果token不存在，直接返回401
        String token = getRequestToken((HttpServletRequest) request);
        if(StringUtils.isBlank(token)){
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());

            httpResponse.setContentType("application/json;charset=utf-8");
            /*String json = JSONObject.fromObject(R.noAccess()).toString();
            httpResponse.getWriter().print(json);*/
            String path = ((HttpServletRequest) request).getContextPath();
            httpResponse.sendRedirect(path);
            return false;
        }

        return executeLogin(request, response);
	}



	 /**
     * 获取请求的token
     */
    private String getRequestToken(HttpServletRequest httpRequest){
        //从header中获取token
        String token = httpRequest.getHeader(Constant.token);

        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)||("null").equals(token)){
            token = httpRequest.getParameter(Constant.token);
        }

        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)||("null").equals(token)){
            Cookie[] cookies =  httpRequest.getCookies();
            if(cookies != null){
                for(Cookie cookie : cookies){
                    if(cookie.getName().equals(Constant.token)){
                        token =  cookie.getValue();
                    }
                }
            }
        }




        return token;
    }
}
